package com.ja.openchat.ui.contact;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentContactListBinding;
import com.ja.openchat.databinding.FragmentContactNewBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.group.GroupSendActivity;
import com.ja.openchat.ui.contact.search.PublicSearchFragment;
import com.ja.openchat.ui.message.AddContactActivity;
import com.ja.openchat.viewmodels.ContactListViewModel;
import com.ja.openchat.views.SideIndexBar;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import me.goldze.mvvmhabit.base.BaseFragment;

public class ContactNewFragment extends BaseFragment<FragmentContactNewBinding, ContactListViewModel>{

    public ContactListAdapter contactListAdapter;
    private List<Section> sectionList = new ArrayList<>();


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_contact_new;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initView() {
        super.initView();
        binding.ivBarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AddContactActivity.class);
            }
        });
        //初始化列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        contactListAdapter = new ContactListAdapter(R.layout.adapter_contact_list, R.layout.adapter_section_contact_list, sectionList);
        binding.recyclerView.setAdapter(contactListAdapter);
        View headerView = getLayoutInflater().inflate(R.layout.header_contact_view,binding.recyclerView,false);
        headerView.findViewById(R.id.search_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(PublicChatSearchActivity.class);
                startContainerActivity(PublicSearchFragment.class.getCanonicalName());
            }
        });
        LinearLayout llConversationGroup = headerView.findViewById(R.id.ll_conversation_group);
        llConversationGroup.setVisibility(View.VISIBLE);
        llConversationGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startContainerActivity(GroupListFragment.class.getCanonicalName());
            }
        });
        LinearLayout llGroupSend = headerView.findViewById(R.id.ll_group_send);
        llGroupSend.setVisibility(View.VISIBLE);
        llGroupSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //群发助手
                startActivity(GroupSendActivity.class);
            }
        });
        contactListAdapter.addHeaderView(headerView);
        //加载数据
        reloadContacts();
        //同步联系人
        TelegramManager.getTelegramManager().syncMyContacts();
        //索引事件
        binding.slide.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        binding.recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
        binding.slide.setOverlayTextView(binding.tvIndicate);
        //点击事件
        contactListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        //跳转个人资料详情
//                        ContactDetailActivity.start(getActivity(), user);
                        TelegramManager.getTelegramManager().createPrivateChat(getContext(), user.id, new TgResultBlock<ChatInfo>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                                if (obj != null) {
                                    ChatActivity.startActivity(getContext(), obj);
                                }
                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {
                            }
                        });
                    }
                }
            }
        });
    }

    public void reloadContacts() {
        sectionList.clear();
        //获取联系人
        List<UserInfo> list = TelegramManager.getTelegramManager().getTgData().getMyContacts();
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        //生成a-z hash
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }
        Map<String, String> defaultMap = new HashMap<>();
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    defaultMap.put(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0)),"");
//                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    defaultMap.put("#","");
//                    sectionMap.get("#").add(user);
                }
            } else {
//                sectionMap.get("#").add(user);
                defaultMap.put("#","");
            }
        }
        List<String> keyList = new ArrayList<>(defaultMap.keySet());
        String[] keys = keyList.toArray(new String[]{} );
        binding.slide.DEFAULT_INDEX_ITEMS = keys;
        binding.slide.setEnableItemHeight(true);
        binding.slide.refresh();

        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : binding.slide.DEFAULT_INDEX_ITEMS) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    sectionList.add(new Section(false, user));
                }
            }
        }
        //刷新页面
        contactListAdapter.notifyDataSetChanged();
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Contact_Photo_Ok:
                contactListAdapter.notifyDataSetChanged();
                break;
            case EUser_Td_UpdateContactInfo:
                reloadContacts();
                break;
            case EUser_Td_AddNewContactInfo: {
                UserInfo user = (UserInfo) tg_event.data;
                if (user.is_contact) {
                    reloadContacts();
                }
            }
            break;
        }
    }


}